package com.kele.user.controller;

import com.kele.utils.BufferedImageUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("user")
public class ImageController {

    @Autowired
    HttpServletResponse response;

    public static final String prefix = "UUID_";
    @Autowired
    RedisTemplate redisTemplate;

    @GetMapping("/image/code/{uuid}")
    public void generatorImage(@PathVariable String uuid) throws IOException {

        response.addHeader("Cache-Control","no-cache");
        response.addHeader("Cache-Control","no-store");
        response.setContentType("image/jpeg");//

        System.out.println("UUID=" + uuid);
        String code = BufferedImageUtils.generateTextCode(BufferedImageUtils.TYPE_ALL_MIXED, 4, null);
        System.out.println("Code=" + code);
        BufferedImage bufferedImage = BufferedImageUtils.generateImageCode(code,
                200, 50, 3, true,
                Color.WHITE, Color.BLACK, null);

        redisTemplate.opsForValue().set(prefix + uuid,code,60, TimeUnit.SECONDS);

        ImageIO.write(bufferedImage,"JPEG",response.getOutputStream());

        response.getOutputStream().close();
    }

}
